<template>
	<el-select v-bind="selectConfig" v-model="selectValues" @visible-change="handleVisibleChange">
		<template v-for="(item, index) in selectOptions">
			<el-option hidden :value="item.id" :label="item.name" />
		</template>
		<el-tree v-bind="treeConfig" :data="treeData" @check-change="handleCheckChange"></el-tree>
	</el-select>
</template>

<script>
export default {
	name: 'swTreeMultiSelect',
	props: {
		size: { type: String, default: '' },
		value: { type: String, default: '' },
		nodeKey: { type: String, default: 'id' },
		placeholder: { type: String, default: '' },
		disabled: { type: Boolean, default: false },
		treeData: { type: Array, default: () => [] },
		defaultProps: {
			type: Object,
			default: () => {
				return { label: 'label', children: 'children' };
			}
		}
	},
	data() {
		return {
			isShowPulldown: false,
			inputValue: this.value,
			selectValues: [],
			selectConfig: {
				ref: 'select',
				multiple: true,
				size: this.size,
				disabled: this.disabled,
				popperAppendToBody: false,
				placeholder: this.placeholder,
				class: 'select_element_wrapper'
			},
			treeConfig: {
				ref: 'selectTree',
				showCheckbox: true,
				nodeKey: this.nodeKey,
				highlightCurrent: true,
				defaultExpandAll: true,
				checkOnClickNode: true,
				expandOnClickNode: false,
				props: this.defaultProps,
				class: 'select_tree_wrapper'
			}
		};
	},
	computed: {
		selectOptions() {
			return this.treeToFlatData(this.treeData);
		}
	},
	watch: {
		value(val) {
			this.inputValue = val;
		},
		inputValue: {
			handler(val) {
				this.$emit('input', val);
				if (!val) {
					this.selectValues = [];
				} else {
					this.selectValues = val.split(',');
				}
			},
			immediate: true
		},
		selectValues(arr) {
			this.inputValue = arr.join(',');
		}
	},
	methods: {
		treeToFlatData(dataSource) {
			let flatArr = [];
			let dataArr = JSON.parse(JSON.stringify(dataSource));
			const flatFunc = (arr) => {
				arr.forEach((item) => {
					flatArr.push(item);
					if (!!item[this.defaultProps.children] && item[this.defaultProps.children].length > 0) {
						flatFunc(item[this.defaultProps.children]);
					}
					delete item[this.defaultProps.children];
				});
			};
			flatFunc(dataArr);
			return flatArr;
		},

		//下拉框显示隐藏
		handleVisibleChange(flag) {
			if (!flag) return false;
			this.$nextTick(() => {
				this.$refs['selectTree'].setCheckedKeys(this.selectValues);
			});
		},

		//树形选择改变
		handleCheckChange(data, checked, indeterminate) {
			this.selectValues = this.$refs['selectTree'].getCheckedKeys();
		}
	}
};
</script>
<style lang="scss" scoped>
.select_element_wrapper::v-deep {
	width: 100%;
	.el-tag__close {
		display: none;
	}
	.el-select-dropdown__item {
		display: none;
		height: auto;
		padding: 0;
		font-weight: normal;
	}
}
.select_tree_wrapper::v-deep {
	.el-tree-node__content {
		height: 32px;
	}
	.el-tree-node__label {
		padding-right: 15px;
	}
}
</style>
